// 引入定义pinia
import { defineStore } from 'pinia';
// 引入数据类型
import { StoreType, UserStoreType, CatBanner, CatSpecial, CatData, Classify, AddressData } from '../types';
// 引入数据请求api
import {
  getCatData,
  getLocalData,
  getGoodsData,
  getClassifyData,
  getSearchData,
  getCartData,
  getAddressData,
  getSettlementDate,
  geocodeAddress,
  getWalletDate,
  getOrderDate
} from '../api'

// 商品类
export const useBaseStore = defineStore('base', {
  state(): StoreType {
    return {
      nowAct: 0,
      // 分类数据
      CatData: [],
      // 首页各个分类的轮播图数据
      CatBanner: { cat_id: "", banner_list: [] },
      // 各个分类专题数据
      CatSpecial: { cat_id: "", special_list: [] },
      // 各个分类及里面小分类数据
      CatGoodsList: [],
      // 分类个体和小分类数据
      Classify: { cat_id: "", title: "", title_img: "", data: [], _id: "" },
      // 小分类的商品数据
      ClassifyGoods: [],
      // 商品详情数据
      GoodsProduct: {
        goods_number: "",
        banner: [],
        product_banner: [],
        lc_recommend: [],
        _id: "",
        brand_name: "",
        goods_id: "",
        cat_id: "",
        goods_name: "",
        price: 0,
        star_number: ""
      },
      //猜你喜欢数据
      guessLikeList: []
    }
  },
  actions: {
    // 保存标签页数据方法
    async getCarData() {
      this.CatData = await getCatData()
      this.getClassifyDataList(this.CatData[0].cat_id);
    },
    // 保存当前小分类数据方法
    async getClassifyDataList(val: string) {
      let result = await getClassifyData();
      this.Classify = result.find((item: any) => item.cat_id == val)
      console.log(this.Classify);
    },
    // 保存轮播图数据
    async getCatBannerData(val: string) {
      let data = await getLocalData("cat_banner_data.json");
      this.CatBanner = data.find((item: CatBanner) => item.cat_id == val) || { cat_id: "", banner_list: [] }
      console.log(this.CatBanner);
    },
    // 保存专题数据
    async getCatSpecialData(val: string) {
      if (val == '0041') return;
      let data = await getLocalData("cat_special_data.json");
      this.CatSpecial = data.find((item: CatSpecial) => item.cat_id == val) || { cat_id: "", special_list: [] };
      console.log(this.CatSpecial);
    },
    // 保存home页商品数据
    async getCatGoodsDataList(val: string) {
      if (val == '0041') {
        let catData: Array<CatData> = await getCatData()
        let promises = catData.map(async (item) => {
          let data = await getGoodsData({ pagesize: "4", catId: item.cat_id });
          return { cat_id: item.cat_id, cat_small_id: item.cat_id, cat_small_name: item.cat_name, goods_list: data };
        })
        this.CatGoodsList = await Promise.all(promises);
        console.log(this.CatGoodsList);
        return;
      }
      let ClassifyList = await getClassifyData()
      let ClassifyItem: Classify = ClassifyList.find((item: any) => item.cat_id == val)
      let promises = ClassifyItem.data.map(async item => {
        let data = await getSearchData({ pagesize: "4", keywords: item.product_content.slice(0, 2) });
        console.log(data);
        return { cat_id: val, cat_small_id: item.id, cat_small_name: item.product_content, goods_list: data }
      });
      this.CatGoodsList = await Promise.all(promises);
      console.log(this.CatGoodsList);
    },
    // 小分类商品数据
    async getClassifyGoods(keywords: string) {
      this.ClassifyGoods = await getSearchData({ keywords: keywords.slice(0, 2) });
    },
    //获取商品详情数据
    async getGoodsProduct(goodsId: string) {
      let result = await getGoodsData({ goodsId: goodsId });
      this.GoodsProduct = result[0];
      console.log(this.GoodsProduct);
    },
    // 获取猜你喜欢数据
    async getGuessLikeList(value: string) {
      this.guessLikeList = await getSearchData({
        pagesize: "8",
        keywords: value
      })
      console.log(this.guessLikeList);
    }
  }
});
//权限类
export const useUserStore = defineStore('user', {
  state(): UserStoreType {
    return {
      // 用户名
      TOKEN: window.localStorage.getItem('token'),
      // 购物车数据
      CartGoods: [],
      // 地址数据
      Address: [],
      // 编辑地址
      AddressEdit: {
        name: "",
        tel: "",
        province: "",
        city: "",
        county: "",
        addressDetail: "",
        areaCode: "",
        isDefault: false
      },
      // 当前地址
      nowAddress: {
        id: "",
        name: "",
        tel: "",
        address: "",
        isDefault: false,
        isCheck: false
      },
      // 结算订单
      SettlementList: [],
      // 钱包余额
      Wallet: "",
      // 获取所有订单
      OrderList: [],
      // 获取当前订单详情
      nowOrder:{
        _id: "",
        token: "",
        goodsName: "",
        price: 0,
        goodsthumb: "",
        goodsNumber: 0,
        orderRemark: "",
        orderAddress: "",
        name: "",
        tel: "",
        time: "",
        statu: 0
      }
    }
  },
  actions: {
    // 获取购物车数据
    async getCartGoods() {
      let result = await getCartData({ status: "viewcart", userId: this.TOKEN });
      console.log(result);
      this.CartGoods = result.data.map((item: any) => {
        return {
          goods_id: item.goods_id,
          goods_name: item.goods_name,
          goods_number: item.goods_number,
          goods_desc: item.goods_desc,
          goods_thumb: item.goods_thumb,
          price: item.price,
          choose: false
        }
      })
      console.log(this.CartGoods);
    },
    // 获取地址数据
    async getAddress(data: object) {
      // 如果还没有获取到值，那么先把默认地址设置为选中地址
      if(!this.Address[0]){
        let response = await getAddressData(data);
        let defaultAddress = response.data.find((item: { isDefault: any; }) => item.isDefault)
        await getAddressData({status: "activeAddress", userId: localStorage.getItem("token"), addressId: defaultAddress.address_id});
      }
      let result = await getAddressData(data);
      this.Address = result.data.map((item: any) => {
        return {
          id: item.address_id,
          name: item.takename,
          tel: item.tel,
          address: item.province + item.city + item.district + item.streetname,
          isDefault: item.isDefault,
          isCheck: item.isActive
        }
      })
      console.log(this.Address);
    },
    // 获取编辑地址
    async getAddressEdit(data: string){
      let result = this.Address.find((item:AddressData)=> item.id == data);
      let response = await geocodeAddress(result?.address || "");
      console.log(result);
      this.AddressEdit = {
        name: result?.name || "",
        tel: result?.tel || "",
        province: response.province,
        city: response.city,
        county: response.district,
        addressDetail: response.formatted_address,
        areaCode: "",
        isDefault: result?.isDefault || false
      }
      console.log(this.AddressEdit);
    },
    // 获取当前选中地址
    async getNowAddress() {
      this.nowAddress = this.Address.find(item => item.isCheck == true) || {
        id: "",
        name: "",
        tel: "",
        address: "",
        isDefault: false,
        isCheck: false
      }
    },
    // 获取结算订单数据
    async getSettlementList(data: object) {
      let result = await getSettlementDate(data);
      this.SettlementList = result.data.map((item: any) => {
        return {
          goods_desc: item.goods_desc,
          goods_id: item.goods_id,
          goods_name: item.goods_name,
          goods_number: item.goods_number,
          goods_thumb: item.goods_thumb,
          price: item.price,
        }
      })
      console.log(this.SettlementList);
    },
    // 获取钱包数据
    async getWallet(data: object){
      this.Wallet = await getWalletDate(data);
    },
    // 获取所有订单
    async getOrderList(){
      this.OrderList = await getOrderDate(localStorage.getItem("token")|| "");
      console.log(this.OrderList);
    }
  }
})

